import React from 'react';
import InputItem from 'antd-mobile/lib/input-item';
import List from 'antd-mobile/lib/list';
import Button from 'antd-mobile/lib/button';
import Toast from 'antd-mobile/lib/toast';
import Modal from 'antd-mobile/lib/modal';
import { Link } from 'react-router-dom';
import getUrlParam from 'shared/utils/getUrlParam';
import fetchJsonp from 'fetch-jsonp';
import BackNav from 'shared/components/BackNav';
import localStorage from 'shared/utils/localStorage';
import { getVerifyTicketApi, getAuthSsoApi } from 'shared/api';
import { loginApi, getImageverifyCodeApi, encryptPhoneApi } from '../api';
import './index.less';

// const wx = require('src/static/wx.jpg');
// const head = require('src/static/loginTouxiang.png');

const serverMsg = {
  20001: '账号不存在',
  20002: '密码错误',
  30013: '验证码过期',
  20005: '需要手机号登录',
  20011: '账号已锁定'
}

export default class Login extends React.Component {
  constructor(props) {
    super(props);
    this.data = {
      mobile: '',
      password: ''
    }

    this.state = {
      verifyCode: '',
      encryptModal: false,
      showRePassWordModal: false
      // loginbg: ''
    }
  }

  componentDidMount() {
    this.getImageverifyCode();
    if (getUrlParam('resetPassword')) {
      this.respasworrd();
    }
    // getLoginImage().then(({ code, data: { loginbg } }) => {
    //   if (code === 1000) {
    //     this.setState({ loginbg })
    //   }
    // })
  }

  getImageverifyCode = () => {
    getImageverifyCodeApi().then(({ code, data }) => {
      if (code === 1000) {
        this.setState({ verifyCode: data.base64codeimage });
      }
    })
  }

  hanldeChange = (key, value) => {
    this.data[key] = value;
  }

  hanldeLogin = () => {
    loginApi(this.data).then((result) => {
      const code = +result.data.result.code;
      this.userInfo = JSON.stringify(result.data);

      if (result.code === 1000) {
        localStorage.setObject('loginData', this.data);
        delete result.data.mobile;
        window.localStorage.setItem('userInfo', this.userInfo);
        const { token, uid } = result.data;
        Toast.success('登录成功');
        localStorage.set('token', token);
        localStorage.set('uid', uid);

        fetchJsonp(getVerifyTicketApi({
          sessionid: localStorage.get('sessId'),
          ticket: token
        }))
          .then(function (response) {
            return response.json()
          })
          .then(function (json) {
          })
        location.href = localStorage.get('preUrl') || '/'
      } else if (serverMsg[code]) {
        Toast.fail(serverMsg[code], 1);
        window.localStorage.setItem('userInfo', '');
      } else if (code === 20012) {
        const { result: res } = result.data
        localStorage.set('token', res.ticket);
        localStorage.set('uid', res.member_id);

        this.impower(res.ticket);

      } else if (code === 20008 || code === 20009) {
        this.respasworrd();
      } else {
        Toast.fail(result.data.result.message, 1);
      }
    })
  }

  // 授权页面
  impower = (ticket) => {
    this.setState({ encryptModal: true })
    this.ticket = ticket;
  }

  //重置密码流程
  respasworrd() {
    this.setState({ showRePassWordModal: true  })
  }

  handleConfirm = () => {
    encryptPhoneApi({ plaintext: this.data.mobile }).then(({ data }) => {
      fetchJsonp(getVerifyTicketApi({
        sessionid: localStorage.get('sessId'),
        ticket: this.ticket
      }))
        .then((response) => {
          return response.json()
        })
        .then((res) => {
          if (+res.code === 1) {
            fetchJsonp(getAuthSsoApi({
              sessionid: localStorage.get('sessId'),
              account: data.encrypttext
            }))
              .then(function (response) {
                return response.json()
              })
              .then(function (result) {

                if (+result.code === 1) {
                  window.localStorage.setItem('userInfo',  this.userInfo);
                  location.reload();
                } else {
                  Toast.fail(result.message, 1);
                }
              })
          } else {
            Toast.fail(res.message, 1);
          }
        })
    })
  }

  redirectFortatPassword = () => {
    window.location.hash = `/forgetPassword?auth=auth`;
  }

  render() {
    const { verifyCode } = this.state;
    return (
      [
        <BackNav title="登录" key='back-nav' to='#/' />
        ,
        <div className="login-content" key="login-content">
          <div className="login-content-title">
            {/* <img src={head} alt='' /> */}
          </div>
          <div className="login-content-form">
            <List>
              <InputItem
                autoFocus
                placeholder="手机号/邮箱/会员账号"
                type="number"
                onChange={(value) => this.hanldeChange('mobile', value)}
              />
              <InputItem
                placeholder="密码"
                type="password"
                onChange={(value) => this.hanldeChange('password', value)}
              />
              <div className="login-module-confilm">
                <InputItem
                  onChange={(value) => this.hanldeChange('verifycode', value)}
                  placeholder="验证码"
                />
                <div className="login-module-confilm-code">
                  <img src={verifyCode} alt='' />
                </div>
                <div className="login-module-confilm-text" onClick={this.getImageverifyCode}>看不清？换一张</div>
              </div>
            </List>
          </div>
          <div className="forget-password">
            <Link to='/register' className="register">立即注册</Link>
            <Link to='/forgetPassword'>忘记密码</Link>
          </div>
          <Button type="warning" className="form-btn" onClick={this.hanldeLogin}>立即登录</Button>
          <Modal
            visible={this.state.encryptModal}
            transparent
            maskClosable={false}
            onClose={()=>this.setState({ encryptModal: false })}
            title="授权页面"
            footer={[{ text: '同意', onPress: this.handleConfirm }]}
          >
            <div style={{ height: 200, overflow: 'scroll', textAlign: 'left' }}>
              <p>
              感谢您对佳能的关注，为提升佳能的用户体验，佳能现推出全新的统一注册登录服务。授权之后，您在当前网站注册的账户和密码可以同时登录佳能（中国）有限公司的其他相关服务平台，目前包括
              <a href="https://club.canon.com.cn/m/home.html">佳能俱乐部官方网站</a>、
              <a href="https://www.photowoo.com/gamenewmob/index">佳画廊官方网站</a>、
              <a href="http://dyj88c.lofter.com/">大影家官方网站</a>、
              <a href="https://shop.canon.com.cn/ecm/#">佳能官方线上商城</a>、
              <a href="https://m.canon.com.cn/m/support/pregister/login/index">佳服务</a>、
              <a href="https://club.canon.com.cn/m/wechat.html">佳能俱乐部微信公众号</a>。
              </p>
            </div>
          </Modal>
          <Modal
            visible={this.state.showRePassWordModal}
            transparent
            maskClosable={false}
            onClose={()=>this.setState({ showRePassWordModal: false })}
            title="注册授权页面"
            footer={[{ text: '下一步', onPress: this.redirectFortatPassword }]}
          >
            <div style={{ height: 200, overflow: 'scroll', textAlign: 'left' }}>
              <p>
              您的手机号码已注册过佳能（中国）有限公司的其他相关服务平台。为了提升佳能的用户体验，佳能现推出全新的统一注册登录服务，统一佳能相关服务平台的账户和密码，因此需要您重置密码。您在当前网站重置后的账户和密码可以同时登录佳能（中国）有限公司的其他相关服务平台，目前包括
              <a href="https://club.canon.com.cn/m/home.html">佳能俱乐部官方网站</a>、
              <a href="https://www.photowoo.com/gamenewmob/index">佳画廊官方网站</a>、
              <a href="http://dyj88c.lofter.com/">大影家官方网站</a>、
              <a href="https://shop.canon.com.cn/ecm/#">佳能官方线上商城</a>、
              <a href="https://m.canon.com.cn/m/support/pregister/login/index">佳服务</a>、
              <a href="https://club.canon.com.cn/m/wechat.html" >佳能俱乐部微信公众号</a>。
              点击“确认”，进入密码重置页面
              </p>
            </div>
          </Modal>

          <div className="other-login">
            {/* <div className="other-login-wx">
              <span>其他登录</span>
              <img src={wx} alt="" />
            </div> */}
          </div>
        </div>
      ]
    );
  }
}